<?php
namespace app\wechat\pay;
/**
 * 微信移动端服务
 */
class WechatWebPay extends \app\base\service\BaseService {

    private $rsa = '';

    private function payConfig($notifyUrl = '') {
        $config = target('member/PayConfig')->getConfig('wechat_mobile');
        if (empty($config['mch_id']) || empty($config['md5_key'])) {
            return $this->error('请先配置支付接口信息!');
        }
        $wechatConfig = target('wechat/WechatConfig')->getConfig();
        if(empty($wechatConfig['appid'])) {
            return $this->error('公众号ID未设置!');
        }
        $notifyUrl = DOMAIN . $notifyUrl;
        return [
            'app_id' => $wechatConfig['appid'],
            'mch_id' => $config['mch_id'],
            'md5_key' => $config['md5_key'],
            'notify_url' => $notifyUrl,
            'time_expire'	=> 5,
        ];
    }

    public function getUrl($data, $returnUrl) {
        if (empty($data)) {
            return $this->error('订单数据未提交!');
        }
        unset($data['user_id']);
        $data['return_url'] = DOMAIN . urldecode($returnUrl);
        $data['tmp'] = time();
        $config = \Config::get('dux.use');
        ksort($data);
        $token = base64_encode(hash_hmac('sha1', http_build_query($data), $config['safe_key'], true));
        $data['token'] = $token;

        $url = url('wechat/WebPay/index') . '?' . http_build_query($data);
        return $this->success($url);
    }


    public function notifyPay($class) {
        if (!is_object($class)) {
            return $this->error('通知类错误!');
        }
        $config = $this->payConfig($notifyUrl = '');
        $notify = new \Payment\NotifyContext();
        $callback = $class;
        try {
            $notify->initNotify(\Payment\Config::WEIXIN, $config);
            return $this->success($notify->notify($callback));
        } catch (PayException $e) {
            return $this->error($e->errorMessage());
        }
    }

}